#-------------------------------------------------------------------------------
# Name:       desktop_frontend.py
# Purpose:    Provide a GUI for conversion
#
# Authors:    Glenn Ramsey <glenn.ramsey@slidespeech.com>
#
# Copyright:  (c) Slidespeech Ltd 2012
# Licence:    MIT license
#-------------------------------------------------------------------------------
"""
The interface will be a small application window with a file menu:
File
    Open...
    Quit

Tools
    Options...
    

There will be several checkboxes to specify output formats:
JSON
HTML
Video

The dialog will have a target area to drop the presentation.
"Drop your presentation file here."

There should be a progress bar.

"""
import sys, os
from functools import partial
import win32api
from PySide.QtGui import QApplication, QMainWindow, QFileDialog, QMessageBox
from PySide.QtCore import Qt, QTimer

from qt.ui_mainwindow import Ui_MainWindow

from converter import ConvertToHTML
from converter_error import ConverterError

from threading import Thread
import Queue

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.setAcceptDrops(True)
        
        self.queue = Queue.Queue()
        
    def Post(self, func):
        if hasattr(func, '__call__'):
            self.queue._put(func)
        else:
            raise RuntimeError("Only callable objects can be posted")
        
    def Poll(self):
        if not self.queue.empty():
           func = self.queue.get_nowait()
           func()
                    
    def Convert(self, infile, outfile, completion_callback):

        p = partial(self._convertThreadFunc, infile, outfile, completion_callback)
        t = Thread(target=p)
        t.start()

    def _convertThreadFunc(self, infile, outfile, completion_callback):
        success = True
        message = None
        try:
            ConvertToHTML(infile, outfile)
        except ConverterError as e:
            import traceback
            print traceback.print_exc()
            success = False
            message = str(e)
        
        f = partial(completion_callback, success, message)
        self.Post(f)    
        
    def dragEnterEvent(self, evt):
        print evt.mimeData().formats()
        if evt.mimeData().hasFormat("FileName"):
            evt.acceptProposedAction()
            # ^ changes the cursor to indicate dropping is allowed

    def dropEvent(self, evt):
        if evt.mimeData().hasFormat("FileName"):
            evt.acceptProposedAction();
            filename = str(evt.mimeData().data("FileName"))
        
            if sys.platform.startswith("win"):
                longpath = win32api.GetLongPathNameW(filename)
            else:
                longpath = filename

            # pop up a save as  dialog
            (path, leafname) = os.path.split(os.path.abspath(longpath))
            (base, suffix) = os.path.splitext(leafname)
            
            savepathList = QFileDialog.getSaveFileName(self,
                   "Save converted presentation as...",
                   os.path.join(path, base+".html.zip")
               )
            
            savepath = ""

            if len(savepathList)>1:
                savepath = savepathList[0]
            
            if "" == savepath:
                return
                                       
            self._orignalLabelText = self.label.text()
            self.label.setText("Converting %s ..." % leafname)
            QApplication.setOverrideCursor(Qt.WaitCursor)

            def conversionComplete(self, success, message):
                QApplication.restoreOverrideCursor()
                if not success:
                    m = QMessageBox(QMessageBox.Warning, "Conversion failed", message, QMessageBox.Ok, self)
                    m.exec_()
                self.label.setText(self._orignalLabelText)
            
            f = partial(conversionComplete, self)
            self.Convert(longpath, savepath, f)
                           
if __name__=="__main__":
    app = QApplication(sys.argv)
    m = MainWindow()
    
    # Create a timer to poll for conversion completion
    t = QTimer()
    t.timeout.connect(m.Poll)
    t.start(100)
    m.show()
    app.exec_()
        